package com.aliyun.heiyu.common.util;

import sun.net.util.IPAddressUtil;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

public class StringUtil {
    /**
     * 验证非零的正整数：^\+?[1-9][0-9]*$
     * 验证非零的负整数：^\-[1-9][0-9]*$
     * 验证非负整数（正整数 + 0） ^\d+$
     * 验证非正整数（负整数 + 0） ^((-\d+)|(0+))$
     * 验证有1-3位小数的正实数：^[0-9]+(.[0-9]{1,3})?$
     * */
    //float ｜｜ double || int
    private static Pattern NUMBER_PATTERN_ONE = Pattern.compile("[-\\+]?\\d*[.]?\\d+$");
    //非负浮点数
    private static Pattern NUMBER_PATTERN_TWO = Pattern.compile("\\d*[.]?\\d+$");
    //非负正数
    private static Pattern NUMBER_PATTERN_THREE = Pattern.compile("^\\d+$");
    //1-3位小树正实数
    private static Pattern NUMBER_PATTERN_FOUR = Pattern.compile("^[0-9]+(.[0-9]{1,3})?$");
    //是否包含特殊字符
    private static Pattern NUMBER_PATTERN_FIVE = Pattern.compile("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]");

    private static Pattern DATE_TIME = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}");

    private static String DATE_REGEX = "^([1-9]\\d{3}-)(([0]{0,1}[1-9]-)|([1][0-2]-))(([0-3]{0,1}[0-9]))$";


    public static boolean equals(String s1, String s2) {
        return s1.equals(s2);
    }

    public static boolean isEmpty(String str){
        if(str == null || str.isEmpty()){
            return true;
        }
        return false;
    }

	public static String fromUTF8ByteArray(byte[] bytes) {
		int i = 0;
		int length = 0;

		while (i < bytes.length) {
			length++;
			if ((bytes[i] & 0xf0) == 0xf0) {
				// surrogate pair
				length++;
				i += 4;
			} else if ((bytes[i] & 0xe0) == 0xe0) {
				i += 3;
			} else if ((bytes[i] & 0xc0) == 0xc0) {
				i += 2;
			} else {
				i += 1;
			}
		}
		char[] cs = new char[length];

		i = 0;
		length = 0;

		while (i < bytes.length) {
			char ch;

			if ((bytes[i] & 0xf0) == 0xf0) {
				int codePoint = ((bytes[i] & 0x03) << 18) | ((bytes[i + 1] & 0x3F) << 12) | ((bytes[i + 2] & 0x3F) << 6)
						| (bytes[i + 3] & 0x3F);
				int U = codePoint - 0x10000;
				char W1 = (char) (0xD800 | (U >> 10));
				char W2 = (char) (0xDC00 | (U & 0x3FF));
				cs[length++] = W1;
				ch = W2;
				i += 4;
			} else if ((bytes[i] & 0xe0) == 0xe0) {
				ch = (char) (((bytes[i] & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f));
				i += 3;
			} else if ((bytes[i] & 0xd0) == 0xd0) {
				ch = (char) (((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
				i += 2;
			} else if ((bytes[i] & 0xc0) == 0xc0) {
				ch = (char) (((bytes[i] & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
				i += 2;
			} else {
				ch = (char) (bytes[i] & 0xff);
				i += 1;
			}

			cs[length++] = ch;
		}

		return new String(cs);
	}

    //校验非负正整数
    public static boolean isPositiveNum(String s){
        return NUMBER_PATTERN_THREE.matcher(s).matches();
    }

    //校验正浮点数float

    //校验浮点数Double
    public static boolean isPositiveDouble(String s){
        return NUMBER_PATTERN_TWO.matcher(s).matches();
    }


    public static int convertInt(String str){
        try{
            double aDouble = Double.valueOf(str);
            int integer = (int)aDouble;
            return integer;
        } catch (Exception e){
        }
        return 0;
    }

    public static double convertDouble(String str){
        try{
            double aDouble = Double.valueOf(str);
            return aDouble;
        } catch (Exception e){
        }
        return 0;
    }

    public static String nullToZero(String str){
        if(str == null || str.isEmpty()){
            return "0";
        }
        return str;
    }

    //校验指定长度字符串
    public static boolean isLength(String s,int min,int max){
        String s1 = s.replaceAll("↵","");
        s1 = s1.replaceAll("\n","");
        int length = s1.length();
        return length<=max&length>=min;
    }


    //校验日期格式
    public static boolean isDateTime(String s){
        return DATE_TIME.matcher(s).matches();
    }

    //校验字节数
    public static boolean isLengthofbit(String s,int min,int max){
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < s.length(); i++) {
            String temp = s.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength<=max&valueLength>=min;
    }

    //校验ipv6
    public static boolean isContainSpecialChar(String s){
        return NUMBER_PATTERN_FIVE.matcher(s).matches();
    }
    
    public static String nullFilter(String str){
        if(null == str){
            return "";
        }
        return str;
    }


    public static int length(String str) {
        return str.length();
    }

    public static String loseBlank(String old) {
        if (isEmpty(old)) {
            return null;
        }
        return old.replaceAll("\\s*", "");
    }


    //校验ip
    public static boolean isIp(String s){

        return MatchIPv4Address(s);
    }

    //校验ipv6
    public static boolean isIpv6(String s){
        return IPAddressUtil.isIPv6LiteralAddress(s);
    }

    /**
     * double类型区间值校验
     * @param num 待校验的值
     * @param min 最小值，num大于min
     * @param max 最大值，num小于max
     * @return
     */
    public static boolean validDoubleInterval(Double num,Double min,Double max){

        return num != null && num <= max && num > min;
    }

    /**
     * 年月日校验
     * @param datestr
     * @return
     */
    public static boolean validDateEffecitive(String datestr){
        boolean matches =  Pattern.matches(DATE_REGEX, datestr);
        if(!matches){
            return matches;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //设置日期格式转的严谨性
        sdf.setLenient(false);
        try {
            sdf.parse(datestr);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return matches;
    }

    public static boolean MatchIPv4Address(String s){
        String range = "(([01][0-9][0-9])|(2([0-4][0-9]|5[0-5]))|([0-9]?[0-9]))";
        String pattern = range+"\\."+range+"\\."+range+"\\."+range;
        Pattern p = Pattern.compile(pattern);
        return p.matcher(s).matches();
    }
}
